<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <!-- 移除错误的 </el-form-item> -->
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input
            v-model="queryParams.deviceNumber"
            placeholder="请输入设备编号"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="currentStatus">
          <el-select
            v-model="queryParams.currentStatus"
            placeholder="设备状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.equipment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['equipment:machine:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['equipment:machine:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['equipment:machine:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['equipment:machine:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="60">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="设备编号" prop="deviceNumber" width="120" />
        <el-table-column label="温度" prop="temperature" width="120" />
        <el-table-column label="湿度" prop="humidity" width="120" />
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.equipment_status" :value="scope.row.currentStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="创建人" prop="createBy" width="120" />
        <el-table-column label="更新人" prop="updateBy" width="120" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="绑定冷库(冷库名)" align="center" width="150">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.lgSubCold" @click="handleUpdate(scope.row)" size="mini" type="primary" v-hasPermi="['equipment:machine:updateVehicle']">绑定冷库</el-button>
            <el-tag v-if="scope.row.lgSubCold" type="success">{{ scope.row.lgSubCold.subName || '未知' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <router-link :to="'/coldThinginfo/'+scope.row.id +'/'" class="link-type" style="margin-right: 15px;">
              <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
          >详细</el-button>
          </router-link>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['equipment:machine:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['equipment:machine:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改角色配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="设备编号" prop="deviceNumber">
            <el-input v-model="form.deviceNumber" placeholder="请输入设备编号" />
          </el-form-item>
          <el-form-item label="温度" prop="temperature">
            <el-input v-model="form.temperature" placeholder="请输入温度" />
          </el-form-item>
          <el-form-item label="湿度" prop="humidity">
            <el-input v-model="form.humidity" placeholder="请输入湿度" />
          </el-form-item>
          <el-form-item label="购买时间" prop="purchaseDate">
            <el-date-picker
              v-model="form.purchaseDate"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择购买时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="状态" prop="currentStatus">
            <el-select
              v-model="form.currentStatus"
              placeholder="设备状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.equipment_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="绑定冷库">
            <el-button
              v-if="form.id && (form.coldStorageId != 0 && form.coldStorageId != undefined)"
              @click="handleCancelBound(form.id)"
              size="mini"
              type="primary"
              v-hasPermi="['equipment:machine:delBound']"
            >取消绑定</el-button>
            <!-- <Index v-if="(!form.id || (form.coldStorageId == 0 || form.coldStorageId == undefined))" :mid="mid" @close="handleCloseDialog"  @selected="handleBigColdSelected"></Index> -->
            <SmallCold v-if="(!form.id || (form.coldStorageId == 0 || form.coldStorageId == undefined))" :mid="mid" @close="handleCloseDialog"  @selected="handleSmallColdSelected"></SmallCold>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>
  import {
    listMachine,
    getMachine,
    updateMachine,
    addMachine,
    delMachine,
    delBound
  } from "@/api/equipment/coldMachine";
  import Index from '@/views/equipment/coldThing/bigCold/index.vue'
  import SmallCold from '@/views/equipment/coldThing/smallCold/index.vue'
  export default {
    components: {
      Index,
      SmallCold
    },
    name: "Role",
    dicts: ['equipment_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        mid: undefined,
        // 角色表格数据
        roleList: [],
        // 弹出层标题
        title: "",
        currentStatus: 1,
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        menuExpand: false,
        menuNodeAll: false,
        deptExpand: true,
        deptNodeAll: false,
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deviceNumber: undefined,
          currentStatus: undefined
        },
        // 表单参数
        form: {
          purchaseDate: null // 初始化购买时间为 null
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          orderNumber: [
            { required: true, message: "订单编号不能为空", trigger: "blur" }
          ],
          deviceNumber: [
            { required: true, message: "设备编号不能为空", trigger: "blur" }
          ],
          temperature: [
            { required: true, message: "温度不能为空", trigger: "blur" }
          ],
          humidity: [
            { required: true, message: "湿度不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        // 假设 addDateRange 方法用于处理日期范围，这里简单返回原参数
        const queryParamsWithDate = this.addDateRange
          ? this.addDateRange(this.queryParams, this.dateRange)
          : this.queryParams;
        listMachine(queryParamsWithDate).then(response => {
          this.roleList = response.rows;
          console.log(response);
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮（数据权限）
      cancelDataScope() {
        this.openDataScope = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.menuExpand = false,
          this.menuNodeAll = false,
          this.deptExpand = true,
          this.deptNodeAll = false,
          this.form = {
            roleId: undefined,
            orderNumber: undefined,
            roleKey: undefined,
            roleSort: 0,
            status: "0",
            menuIds: [],
            deptIds: [],
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            remark: undefined
          };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 选择车辆后关闭弹窗 */
      handleCloseDialog() {
        this.open = false; // 关闭弹窗
        this.getList();    // 可选：刷新数据
      },
      // 处理车辆选择
      handleSmallColdSelected(subId) {
        // 更新表单中的冷库绑定信息
        console.log('Selected coldId:', subId);
        this.form.coldStorageId = subId;
        // 或者直接刷新列表数据
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleDataScope":
            this.handleDataScope(row);
            break;
          case "handleAuthUser":
            this.handleAuthUser(row);
            break;
          default:
            break;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加角色";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const machineId = row.id || this.ids;
        getMachine(machineId).then(response => {
          this.form = response.data;
          this.mid = response.data.id;
          this.form.currentStatus = this.form.currentStatus.toString();
          // 确保购买时间格式正确，修改为精确到时分秒的格式
          this.form.purchaseDate = this.parseTime(response.data.purchaseDate, '{y}-{m}-{d} {h}:{i}:{s}');
          // 确保 form.id 和 form.coldStorageId 正确设置
          console.log('form.id:', response);
          this.form.id = response.data.id;
          this.form.coldStorageId = response.data.coldStorageId; // 添加这一行
          this.open = true;
          this.title = "修改设备";
        });
      },
      /** 选择角色权限范围触发 */
      dataScopeSelectChange(value) {
        if(value !== '2') {
          this.$refs.dept.setCheckedKeys([]);
        }
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              this.form.updateBy = this.$store.getters.name;
              // 打印 form 对象，确认 coldStorageId 是否存在
              console.log('提交的表单数据:', this.form);
              updateMachine(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.createBy = this.$store.getters.name;
              // 打印 form 对象，确认 coldStorageId 是否存在
              console.log('提交的表单数据:', this.form);
              addMachine(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 取消绑定 */
      handleCancelBound(id) {
        this.$modal.confirm("确认要取消该绑定？").then(() => { // 改用箭头函数保持this指向
          return delBound({ id: id }); // 确保参数结构匹配接口要求
        }).then(() => {
          this.$modal.msgSuccess("解绑成功");
          this.open = false;  // 关闭弹窗
          this.getList();     // 重新加载数据
        }).catch(() => {});
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const machineIds = row.id || this.ids;
        this.$modal.confirm(`是否确认删除 id 为 "${machineIds}" 的数据项？`).then(() => { // 使用箭头函数
          return delMachine(machineIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        // 假设 download 方法用于下载文件，这里简单给出提示
        if (!this.download) {
          console.error('download 方法未定义');
          return;
        }
        this.download('equipment/machine/export', {
          ...this.queryParams
        }, `GPSMachine_${new Date().getTime()}.xlsx`);
      },
      // 补充 addDateRange 方法（示例）
      addDateRange(params, dateRange) {
        if (dateRange && dateRange.length === 2) {
          params.startDate = dateRange[0];
          params.endDate = dateRange[1];
        }
        return params;
      },
      // 补充 download 方法（示例）
      download(url, params, filename) {
        // 这里可以实现具体的下载逻辑
        console.log('开始下载', url, params, filename);
      }
    }
  };
  </script>
